package com.yixun.qfbao.hander.base;

import com.alibaba.fastjson.JSON;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.dto.base.DefaultRes;
import com.yixun.qfbao.dto.base.OvalUtil;
import com.yixun.qfbao.dto.exception.OvalUNCheckedException;
import com.yixun.qfbao.dto.exception.XFUNCheckedException;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;

public abstract class CommonAbstractHander {
	private static Logger logger = LoggerFactory.getLogger(CommonAbstractHander.class);

	public BaseResponseDTO hander(BaseRequestDTO reqDto) {
		logger.info("API业务处理开始:=> API: {}, Request Body: {}", this.getClass().getName(), JSON.toJSON(reqDto));
		BaseResponseDTO resDto = null;
		try {
			// 验签
			// 参数有效性验证
			OvalUtil.validate(reqDto.getParams());
			// 业务处理
			resDto = doBusiness(reqDto);
		} catch (OvalUNCheckedException e) {
			resDto = new BaseResponseDTO<DefaultRes>();
			DefaultRes defaultRes = BaseResponseDTO.getDefaultResDto();
			defaultRes.setErrorMsg(e.getMessage());
			defaultRes.setErrorCode(e.getCode());
			resDto.setResData(defaultRes);
			resDto.setResult(e.getCode());
			logger.info("API业务处理结束:=> API: {}, Request Body: {}", this.getClass().getName(), e);
		} catch (XFUNCheckedException e) {
			DefaultRes defaultRes = BaseResponseDTO.getDefaultResDto();
			defaultRes.setErrorMsg(e.getOutMsg());
			defaultRes.setErrorCode(e.getCode());
			resDto.setResData(defaultRes);
            logger.error("API业务处理结束:=> API: {}, Request Body: {}", this.getClass().getName(), e);
		} catch (Exception e) {
			String errorMsg = e.getMessage();
			resDto = new BaseResponseDTO<DefaultRes>();
			DefaultRes defaultRes = BaseResponseDTO.getDefaultResDto();
			defaultRes.setErrorMsg(errorMsg);
			resDto.setResData(defaultRes);
            logger.error("API业务处理结束:=> API: {}, Request Body: {}", this.getClass().getName(), e);
		} finally {
			// 记录日志
            logger.info("API业务处理结束:=> API: {}, Request Body: {}", this.getClass().getName(), JSON.toJSON(resDto));
		}
		// 返回结果
		return resDto;
	}
	
	public Object hander(BaseRequestDTO<?> request, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			BaseResponseDTO<Object> responseDTO=new BaseResponseDTO<>();
			responseDTO.setResult(ResultEnum.FAIL.getNo());
			responseDTO.setResData(bindingResult.getFieldError());
			responseDTO.setErrorMsg("参数验证失败！");
			return responseDTO;
		}
		return hander(request);
	}
	
	public abstract BaseResponseDTO doBusiness(BaseRequestDTO reqDto);
}
